<template>
  <div class='table'>
    <ui-container style="width:100%">
      <div class='t_top'>
        <el-select v-model="status" placeholder="请选择" size="small">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-input
          placeholder="活动编号"
          v-model="input"
          size="small"
          clearable style="width:300px">
        </el-input>
        <el-button type="primary" size="small" @click="search()" >查询</el-button>
        
      </div>
    </ui-container>
    <ui-container style='margin-top:15px' v-loading="loading">
      <div style="text-align:right;" class="btn-row">
        <el-button type="success" size="small" @click="add">新增活动</el-button>
        <el-button type="success" size="small" @click="handleUpdate">修改活动</el-button>
        <el-button type="danger" size="small" @click="updateStatus">禁用/启用活动</el-button>
        <el-button type="danger" size="small" @click="handleClick">删除活动</el-button>
      </div>
      <div class='t_bottom' style="width:100%; font-size:14px;">
        <el-table
          ref='multipleTable'
          :data='tableData'
          tooltip-effect='light'
          style='width:100%'
          border
        >
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column prop='No' label='活动编号' width='120'></el-table-column>
          <el-table-column prop='Name' label='活动标题' width='120'></el-table-column>
          <el-table-column prop="Photo" label="活动图片" width='120'>
            <template slot-scope="scope">
              <img :src="scope.row.Photo" style="width:120px;height:120px;" />
            </template>
          </el-table-column>
          <el-table-column prop='TypeStr' label='有效时间' width='300'>
            <template slot-scope="scope">
              <span>{{scope.row.StartTimeStr}} - {{scope.row.EndTimeStr}}</span>
            </template>
          </el-table-column>  
          <el-table-column prop='TypeStr' label='活动类型'>
          </el-table-column>
          <el-table-column prop='IntegralAmount' label='活动赠送的积分'>
          </el-table-column>
          <el-table-column prop='Multiple' label='账单转换积分倍数' width='140'>
          </el-table-column>
          <el-table-column prop='IsEnable' label='是否启用' width='80'>
            <template slot-scope="scope">
              <span>{{scope.row.IsEnable?'是':'否'}}</span>
            </template>
          </el-table-column>
           <el-table-column prop='Remark' label='活动内容'>
          </el-table-column>
        </el-table>
        <div class="pagination-row">
          <el-pagination
            background
            layout="total,prev, pager, next,sizes"
            :total="totalNum">
          </el-pagination>
        </div>
      </div>
    </ui-container>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm" style="padding-right:30px;">
        <el-form-item label="活动名称" prop="Name" required>
          <el-input v-model="ruleForm.Name" style="width:400px" size="small"></el-input>
        </el-form-item>
        <el-form-item label="活动图片" prop="Photo">
          <el-upload
            name="Photo"
            class="avatar-uploader"
            action="/api/common/uploadImages"
            :headers="{authorization:token}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm.Photo" :src="ruleForm.Photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动类型" prop="Type" required>
          <el-select v-model="ruleForm.Type" style="width:400px" size="small" placeholder="请选择活动类型">
            <el-option label="固定积分活动" value="0"></el-option>
            <el-option label="倍数积分活动" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="Time" required>
          <el-date-picker
            v-model="ruleForm.Time"
            size="small"
            format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动赠送积分金额" prop="IntegralAmount"  v-if="ruleForm.Type==='0'" required>
          <el-input v-model="ruleForm.IntegralAmount" style="width:400px" size="small"></el-input>
        </el-form-item>
        <el-form-item label="账单转换积分倍数" prop="Multiple" v-if="ruleForm.Type==='1'" required>
          <el-input v-model="ruleForm.Multiple" style="width:400px" size="small"></el-input>
        </el-form-item>
        <el-form-item label="活动内容" prop="Remark" required>
          <el-input type="textarea" v-model="ruleForm.Remark" rows="5"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" size="small">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type='text/javascript'>
import {cookieStorage} from 'src/common/storage'
export default {
  name: 'activityList',
  data () {
    return {
      statusList:[{
          value: '',
          label: '全部'
        }, {
          value: 'true',
          label: '启用'
        }, {
          value: 'false',
          label: '禁用'
        }],
      title:'设置活动',
      pickerOptions: { // 
      　　disabledDate(time) {
      　　　　return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
      　　}
      },
      status:'',
      loading: false,
      input: '',
      editId:0,
      tableData: [],
      totalNum:0,
      pageIndex:1,
      pageSize:10,
      token:cookieStorage.get('authorization'),
      dialogFormVisible: false,
      imageUrl: '',
      ruleForm: {
          Name: '',
          Time:'',
          No:'',
          Type: '0',
          IntegralAmount: 0,
          Multiple: 0,
          Remark: '',
          Photo:''
        },
        rules: {
          Name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' }
          ],
          Type: [
            { required: true, message: '请选择活动类型', trigger: 'change' }
          ],
          Time: [
            { required: true, message: '请选择活动时间', trigger: 'change' },
          ],
          IntegralAmount: [
            { required: true, message: '请输入活动赠送积分金额', trigger: 'change' }
          ],
          Multiple: [
            { required: true, message: '请输入账单转换积分倍数', trigger: 'change' }
          ],
          Remark: [
            { required: true, message: '请输入活动内容', trigger: 'blur' }
          ],
          Photo: [
            { required: true, message: '请上传活动图片', trigger: 'change' }
          ],
        }
    }
  },
  mounted () {
     this.init();
  },
  methods: {
    search(){
      this.pageIndex = 1;
      this.init();
    },
    init(){
      this.loading=true;
      var data = {};
      if(this.status!=='')
      {
        data = {
          No: this.input,
          IsEnable: eval(this.status),
          PageIndex: this.pageIndex,
          PageSize: this.pageSize
        }
      }else{
        data = {
          No: this.input,
          PageIndex: this.pageIndex,
          PageSize: this.pageSize
        }
      }

      this.$api.activity.list(data).then((rs) => {
        console.log(rs)
        this.tableData = rs.Data.Data;
        this.totalNum = rs.Data.TotalNum;
        this.loading=false;
      }).catch((res) =>{this.loading=false;})
    },
    handleClick(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      this.open(id);
    },
    open(index) {
      this.$confirm('此操作将永久删除 , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.activity.del(index).then((rs) => {
        if(rs.IsSuccess){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.init();
          }
        }).catch((res) =>{})
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    updateStatus(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      let IsEnable = selected[0].IsEnable;
      this.loading=true;
      this.$api.activity.updateStatus(id, !IsEnable).then((rs) => {
        this.init();
      }).catch((res) =>{this.loading=false;})
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.StartTime=this.msToDate(this.ruleForm.Time[0]).hasTime;
          this.ruleForm.EndTime=this.msToDate(this.ruleForm.Time[1]).hasTime;
          this.$api.activity.set(this.ruleForm).then((rs) => {
            if(rs.IsSuccess){
              this.$message({
                type: 'success',
                message: '提交成功!'
              });
              this.dialogFormVisible=false;
              this.init();
            }
          }).catch((res) =>{
            // this.loading=false;
            // this.dialogFormVisible=false;
            
          })
        } else {
          this.$message.error('提交失败！');
          //this.dialogFormVisible=false;
          return false;
        }
      });
    },
    handleUpdate(){
      let selected = this.$refs.multipleTable.selection;
      if (selected.length !== 1) {
          this.$message.error("请选择一条数据！");
          return;
      }
      let ids = [];
      ids = ids.concat(selected.map(m => m.Id));
      let id = ids[0];
      this.editId=id;
      this.$api.activity.get(id).then((rs) => {
        if(rs.IsSuccess){
          //this.ruleForm=rs.Data;
          this.ruleForm.Name = rs.Data.Name;
          this.ruleForm.IntegralAmount = rs.Data.IntegralAmount;
          this.ruleForm.Remark = rs.Data.Remark;
          this.ruleForm.Multiple = rs.Data.Multiple;
          this.ruleForm.Photo = rs.Data.Photo;
          this.ruleForm.No = rs.Data.No;
          this.ruleForm.Time=[new Date(rs.Data.StartTime), new Date(rs.Data.EndTime)];
          this.ruleForm.Type=this.ruleForm.Type.toString();
          this.dialogFormVisible=true;
          }
        }).catch((res) =>{})
    },
    add(){
      this.dialogFormVisible = true;
      this.ruleForm.Name= '';
      this.ruleForm.Time='';
      this.ruleForm.Type= '0';
      this.ruleForm.IntegralAmount= 0;
      this.ruleForm.Multiple= 0;
      this.ruleForm.Remark= '';
      this.ruleForm.Photo='';
      this.ruleForm.No='';
      setTimeout(()=>{
        this.$refs['ruleForm'].resetFields();
      },500)
    },
    handleAvatarSuccess(res, file) {
      this.ruleForm.Photo = res;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    msToDate (msec) {
    let datetime = new Date(msec);
    let year = datetime.getFullYear();
    let month = datetime.getMonth();
    let date = datetime.getDate();
    let hour = datetime.getHours();
    let minute = datetime.getMinutes();
    let second = datetime.getSeconds();

    let result1 = year + 
                 '-' + 
                 ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                 '-' + 
                 ((date + 1) < 10 ? '0' + date : date) + 
                 ' ' + 
                 ((hour + 1) < 10 ? '0' + hour : hour) +
                 ':' + 
                 ((minute + 1) < 10 ? '0' + minute : minute) + 
                 ':' + 
                 ((second + 1) < 10 ? '0' + second : second);

    let result2 = year + 
                 '-' + 
                 ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                 '-' + 
                 ((date + 1) < 10 ? '0' + date : date);

    let result = {
        hasTime: result1,
        withoutTime: result2
    };

    return result;
}
  }
}
</script>
<style lang='scss' type='text/scss' rel='stylesheet/scss'>
.container-main{
  width: 100% !important;
}
.table {
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .btn-row{
    margin-bottom:10px;
  }
  .btn-row .el-button+.el-button{
    margin-left:0px;
  }
</style>
